//地址本弹出选择框，针对原KPI系统的组织架构 
//@auth xiangsf 2013-3-15
// constructor for sdAddressBook
//@auth Lin 2017-03-02 1、增加每个属性的注释;2、支持打开弹出框及新窗口的方式;
$.sdAddressBook = function(options) {
	this.settings = $.extend(true, {}, $.sdAddressBook.defaults, options );
	$.sdAddressBook.settings = this.settings;
	if(this.settings.openType == 'windows'){
		this.initWindows();
	}else{
	 	this.init();
	}
};

$.sdAddressBook.settings = function(settings){
	return settings;
}

$.sdAddressBook.parseValues = function(str){
	if(!str || $.trim(str).length == 0) return [];
	var arrays = [];
	var objs = str.split($.sdAddressBook.consts.objSeparator);
	for(var i = 0; i < objs.length ; i++){
		var vs = objs[i].split($.sdAddressBook.consts.separator);
		arrays.push({id : vs[2],name : vs[1], type : vs[0], value : objs[i]});
	}
	return arrays;
};
$.sdAddressBook.parseValue = function(str){
	if(!str || $.trim(str).length == 0) return null;
	var objs = str.split($.sdAddressBook.consts.separator);
	return {id : objs[2],name : objs[1], type : objs[0], value : str};
}
$.sdAddressBook.compNames = function(data){
	var names = "";
	for(var i = 0 ;i < data.length; i++){
		if(names.length > 0) names += ",";
		names += data[i].name;
	}
	return names;
};
$.sdAddressBook.compValues = function(data){
	var values = "";
	for(var i = 0 ;i < data.length; i++){
		if(values.length > 0) values += ",";
		values += data[i].value;
	}
	return values;
};

/*
 * 用打开窗口的方式回调的方法
 */
$.sdAddressBook.winCallback = function(msg){
 	if(msg.hasOk){
  		msg.values = $.sdAddressBook.compValues(msg.data);
		msg.names = $.sdAddressBook.compNames(msg.data);
		if(document.getElementById($.sdAddressBook.settings.txtFieldId)){
			if($("#"+$.sdAddressBook.settings.txtFieldId).val){
				$("#"+$.sdAddressBook.settings.txtFieldId).val(msg.names);
			}else{
				$("#"+$.sdAddressBook.settings.txtFieldId).html(msg.names);
			}
			if($("#"+ $.sdAddressBook.settings.valFieldId).val){
				$("#"+$.sdAddressBook.settings.valFieldId).val(msg.values);
			}else{
				$("#"+$.sdAddressBook.settings.valFieldId).html(msg.values);
			}
		}
		if($.sdAddressBook.settings.callback){
			$.sdAddressBook.settings.callback(msg);
		}
	}
};

$.extend($.sdAddressBook, {
	consts : {
		objSeparator : ",",
		separator : "!@!"
	},
	defaults:{
		openType:"dialog", //可以选择两种打开方式[弹出框、新窗口] 默认为弹出框[dialog,windows]
		url :  baseURL+"/addressbook/addressbook/frame.do",
		type : 16,//1：我的收藏夹;2:组织架构;4:我的公司;8:我的部门;16:我的可管理部门;32:指定组织选择;64:角色选择;128:岗位选择;256:群组选择;512:区域选择; {@link com.shengdai.brms.addressbook.AddressBookRegister}
		defaultChecked : 16,//默认展开的面板（我的可管理部门）
		selectType : [0,20],//0:部门;10:岗位;20:用户;21:用户信息;30群组;40:角色;50:专业线;60:区域;100:规则（抽象处理人之类的）; {@link com.shengdai.brms.system.OrgType}
		num: 0, //小于等于0代表不限制选定对象个数
		oids : "",//限制在这个范围内 eg.:"id1,id2,id3"
		txtFieldId : "inputTxt",
		valFieldId : "inputVal",
		callback : function(){}
	},
	prototype: {
		init: function() {
			var _this = this;
			$.ligerDialog.open({
				url: this.settings.url+(this.settings.url.indexOf("?")>0 ? "&" : "?")+$.param(this.settings),
				height: 530,
				width: 900,
				title : "地址本选择",
				buttons: [
				{ text: '取消', className: 'fa fa-close',
					onclick: function (item, dialog) { dialog.close(); } } ,
				    {text: '确定', className: 'fa fa-check',
						onclick: function (item, dialog) {
							dialog.frame.FF_Confirm(function(msg){
								if(msg.hasOk){
									dialog.close();
									msg.values = $.sdAddressBook.compValues(msg.data);
									msg.names = $.sdAddressBook.compNames(msg.data);
									if(document.getElementById(_this.settings.txtFieldId)){
										if($("#"+_this.settings.txtFieldId).val){
											$("#"+_this.settings.txtFieldId).val(msg.names);
										}else{
											$("#"+_this.settings.txtFieldId).html(msg.names);
										}
										if($("#"+_this.settings.valFieldId).val){
											$("#"+_this.settings.valFieldId).val(msg.values);
										}else{
											$("#"+_this.settings.valFieldId).html(msg.values);
										}
									}
									if(_this.settings.callback){
										_this.settings.callback(msg);
									}
								}
							});
						} 
				    }
				] 
			});
		},
		initWindows:function(){
			//var _this = this;
			window.open(this.settings.url+(this.settings.url.indexOf("?")>0 ? "&" : "?")+$.param(this.settings), "_blank");
		}
	}
});


(function($){
	$.extend($.fn, {
		addressBook : function(options){
			return new $.sdAddressBook(options);
		}
	});
	$.extend($.fn, {
		sdAddressBook : function (options){
			 options = options || {};
			 options = $.extend(true, {
				 type : 20, //可以选择的数据类型，对应OrgType整型值;20：选人
				 multi : 'n', //单选为1,多选为n,数字为不超过该值选择
				 manage : 3, //弹出的地址本内数据类型，比如全组织，我的部门，我的可管理部门，角色，群组等，由业务定义，3代表“我的可管理部门”
				 targetTextId : 'targetTextId',
				 targetValueId : 'targetValueId',
				 onReturn : undefined,
				 orgids : undefined,
				 callback : '' //example:{callback:functionName}; added by yangzengcai 2015-04-08
				}, options);
			 var datas = {};
			 var url = baseURL+"/web/system/dlg/org_select_dlgPage.jsp?type="+options.type+"&manage="+options.manage+"&multi="+options.multi+"&oids="+options.orgids;
			 
			 var ttext = $("#"+options.targetTextId);
			 if(!ttext){
				 alert('没有设置textID');
				return;
			 }
			 var tvalue = $("#"+options.targetValueId);
			 if(!tvalue){
				 alert('没有设置valueID');
				return;
			 }
			 var selectedText = ttext.val() || ttext.html();
			 var selectedValue = tvalue.val() || tvalue.html();
			 
			 var args = {targetTypeText:selectedText,targetTypeValue:selectedValue};
			 if(window.showModalDialog){
				 var result = window.showModalDialog(url,args,"dialogWidth:900px; dialogHeight:560px");
				 afterReturnValue(result, ttext, tvalue);
			 }else{
				 var win = $.openWindow({url:url, width:900,height:560,resizable:false,name:"sdAddressBook"});
				 $(win).bind("unload", function(){
					 var result = win.returnValue;
					 afterReturnValue(result, ttext, tvalue);
				 });
			 }
			 function afterReturnValue(result, ttext, tvalue){
					if(options.onReturn){
						 options.onReturn(result);
					 }
					 //有返回值，说明是确定的，则赋值到指定域中
					 if(result){
						 if(ttext.val){
							 ttext.val(result.outputText);
						 } else{
							 ttext.html(result.outputText);
						 }
							 
						  if(tvalue.val){
							  tvalue.val(result.outputValue);
						  }else{
							  tvalue.html(result.outputValue);
						  }
						 if(result.outputDatas)
							 datas = eval('(' + result.outputDatas + ')');
					 }
					 if (options.callback != '' && result != undefined) {
						 options.callback(result);
					 }
				return false;
			}
	        return datas;
	    },
	    sdAddressBookValue : function (result){
	    	var id , name , type;
	    	if(result && $.trim(result) != ''){
	    		var temp = result.replace(/!@!/g, ',').split(',');
	    		id = temp[2];
	    		name = temp[1];
	    		type = temp[0];
	    	}
			return {
				getValueId : function(){
					return id;
				},
				getValueName : function (){
					return name;
				},
				getValueType : function(){
					return type;
				}
			};
	    }
	});
})(jQuery);